package cola.rh.System.common.jwt;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @Name: JwtHelper
 * @Author: Cola
 * @Time: 2023/3/9 22:18
 * @Description: JwtHelper
 */
public class JwtHelper {
    /*设置 Token 过期时间*/
    private static long tokenExpiration = 7 * 24 * 60 * 60 * 1000;
    /*设置盐值*/
    private static String tokenSignKey = "Cola";

    /**
     * 根据 id 和 用户名生成 token
     *
     * @param userId   userId
     * @param username username
     * @return token
     */
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                /*分类*/
                .setSubject("AUTH-USER")

                /*设置token有效时长*/
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))

                /*设置主体部分*/
                .claim("userId", userId)
                .claim("username", username)

                /*签名部分*/
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    /**
     * 从生成 token 字符串获取用户 id
     *
     * @param token token
     * @return id
     */
    public static Long getUserId(String token) {
        try {
            if (StringUtils.isEmpty(token)) return null;

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 从生成token字符串获取用户名称
     *
     * @param token token
     * @return username
     */
    public static String getUsername(String token) {
        try {
            if (StringUtils.isEmpty(token)) return "";

            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String) claims.get("username");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
